import { getApiClient } from '../utils/api';
import { useRuntimeConfig, useHead } from '#app';

export function useArticles(initialParams = {}) {
  const config = useRuntimeConfig();
  const route = useRoute();

  // SEO 增强状态管理
  const seoState = reactive({
    canonicalUrl: computed(() => `${config.public.siteUrl}${route.path}`),
    paginationMeta: null
  });

  // 核心数据状态
  const {
    data, error, pending, refresh
  } = useAsyncData(
      `articles-${JSON.stringify(initialParams)}-p${route.query.page || 1}`,
      async () => {
        try {
          const pageNum = Number(route.query.page) || 1;
          const response = await getApiClient().get('/app/article/list', {
            params: {
              ...initialParams,
              pageNum,
              pageSize: 20,
              _timestamp: process.server ? Date.now() : undefined // 服务端缓存控制
            }
          });

          if (response?.code === 200) {
            // 结构化数据生成
            const structuredData = generateArticleSchema(response.rows);

            // 分页SEO元数据
            seoState.paginationMeta = buildPaginationMeta(
                response.total,
                pageNum,
                20
            );

            return {
              articles: response.rows,
              total: response.total,
              structuredData,
              trending: response.trending,
              ranks: response.authorRanks
            };
          }
          throw new Error(response?.message || 'Invalid response');
        } catch (err) {
          console.error('SSR Fetch Error:', err);
          return {
            articles: [],
            total: 0,
            structuredData: null,
            trending: [],
            ranks: []
          };
        }
      },
      {
        lazy: false,
        server: true,
        transform: (res) => {
          // 服务端注入SEO元数据
          useHead({
            title: `Page ${route.query.page || 1} | ${config.public.siteName}`,
            meta: [
              {
                name: 'description',
                content: `Discover articles on page ${route.query.page || 1}. ${res.articles[0]?.excerpt || ''}`
              },
              // 分页协议
              ...(seoState.paginationMeta
                  ? [
                    {
                      rel: 'prev',
                      href: seoState.paginationMeta.prev
                    },
                    {
                      rel: 'next',
                      href: seoState.paginationMeta.next
                    }
                  ]
                  : [])
            ],
            link: [
              {
                rel: 'canonical',
                href: seoState.canonicalUrl
              }
            ],
            script: res.structuredData
                ? [{
                  type: 'application/ld+json',
                  innerHTML: JSON.stringify(res.structuredData)
                }]
                : []
          });
          return res;
        }
      }
  );

  // 客户端加载更多（SEO优化版）
  const loadMore = async () => {
    if (pending.value || !data.value || data.value.total <= data.value.articles.length) return;

    try {
      const nextPage = Math.ceil(data.value.articles.length / 20) + 1;
      const response = await getApiClient().get('/app/article/list', {
        params: {
          ...initialParams,
          pageNum: nextPage,
          pageSize: 20,
          _noindex: 1 // 告知API这是客户端分页
        }
      });

      if (response?.code === 200) {
        data.value.articles.push(...response.rows);

        // 动态更新结构化数据
        const newStructuredData = generateArticleSchema(response.rows);
        updateClientSEO(newStructuredData);
      }
    } catch (err) {
      console.error('CSR Load Error:', err);
    }
  };

  // 客户端SEO更新方法
  const updateClientSEO = (newData) => {
    useHead({
      script: [{
        type: 'application/ld+json',
        innerHTML: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "ItemList",
          "itemListElement": [
            ...(data.value.structuredData?.itemListElement || []),
            ...newData.itemListElement
          ]
        })
      }]
    });
  };

  // 分页元数据生成器
  const buildPaginationMeta = (total, currentPage, pageSize) => {
    const totalPages = Math.ceil(total / pageSize);
    return {
      prev: currentPage > 1
          ? `${config.public.siteUrl}${route.path}?page=${currentPage - 1}`
          : null,
      next: currentPage < totalPages
          ? `${config.public.siteUrl}${route.path}?page=${currentPage + 1}`
          : null,
      current: currentPage
    };
  };

  // Schema.org生成器
  const generateArticleSchema = (articles) => {
    return {
      "@context": "https://schema.org",
      "@type": "ItemList",
      "itemListElement": articles.map((article, index) => ({
        "@type": "ListItem",
        "position": index + 1,
        "item": {
          "@type": "Article",
          "name": article.title,
          "url": `${config.public.siteUrl}/article/${article.id}`,
          "author": {
            "@type": "Person",
            "name": article.author
          },
          "datePublished": article.publishDate
        }
      }))
    };
  };

  return {
    articles: data.value?.articles || [],
    trending: data.value?.trending || [],
    ranks: data.value?.ranks || [],
    isLoading: pending.value,
    error: error.value,
    loadMore,
    refresh
  };
}
